#! /usr/bin/env python
"""Skeleton project file mainloop for new OLPCGames users"""
import olpcgames, pygame, logging 
from pygame.locals import *
from olpcgames import pausescreen, mesh

log = logging.getLogger( 'minichat run' )
log.setLevel( logging.DEBUG )

SIZE=48

def main():
    """The mainloop which is specified in the activity.py file
    
    "main" is the assumed function name
    """
    size = (800,600)
    if olpcgames.ACTIVITY:
        size = olpcgames.ACTIVITY.game_size
    screen = pygame.display.set_mode(size)
    
    clock = pygame.time.Clock()

    pygame.init()
    WHITE = (255,255,255)
    GRAY = (128,128,128)
    YELLOW = (255,255,0)
    BLUE = (0,0,255)
    BLACK = (0,0,0)

    font = pygame.font.Font(None, SIZE)

    renderedChars = {}
    def getChar(char):
        if char not in renderedChars:
            renderedChars[char] = font.render(char, True, WHITE)
        return renderedChars[char]

    def insertar(linea, colores=(WHITE, BLACK)):
        color_texto, color_fondo = colores
        screen.blit(screen,(0,-SIZE),screen.get_rect(height=screen.get_rect().height-SIZE))
        lineaSurf = font.render(linea, True, color_texto)
        screen.fill(color_fondo, screen.get_rect(height=SIZE, bottom=screen.get_rect().bottom-SIZE))
        screen.blit(lineaSurf, lineaSurf.get_rect(bottom=screen.get_rect().bottom-SIZE))

    def limpiar():
        screen.fill(BLUE, screen.get_rect(height=SIZE, bottom=screen.get_rect().bottom))

    def enviar(texto):
        mesh.broadcast(texto)

    running = True
    clock = pygame.time.Clock()

    linea = []
    amigos = {}

    def getColores(handle):
        props = amigos.get(handle)
        if props is None:
            return [WHITE, GRAY]
        log.info("using color..." + props.color)
        return [ [ord(cc) for cc in c.decode("hex")] for c in props.color.replace("#","").split(",")]

    def getNombre(handle):
        props = amigos.get(handle)
        if props is None:
            return "<alguien>"
        return props.nick

    x = 0

    tick = 0
    limpiar()
    pygame.display.flip()

    while running:
        milliseconds = clock.tick(25) # maximum number of frames per second
        
        # Event-management loop with support for pausing after X seconds (20 here)
        events = pausescreen.get_events(10*60)
        # Now the main event-processing loop
        if events:
            for event in events:
                if event.type == pygame.QUIT:
                    running = False

                if event.type == olpcgames.MESSAGE_MULTI:
                    #color = WHITE if event.handle == mesh.my_handle() else YELLOW
                    colores = getColores(event.handle)
                    texto = getNombre(event.handle) + ": " + event.content
                    insertar(texto, colores)

                if event.type == KEYDOWN:
                    if event.key == K_RETURN:
                        limpiar()
                        texto = "".join(linea)
                        enviar(texto)
                        linea = []
                        x = 0
                    else:
                        char = event.unicode
                        if char is not None:
                            charSurface = getChar(char)
                            screen.blit(charSurface, charSurface.get_rect(bottom=screen.get_rect().bottom, left=x))
                            x += charSurface.get_rect().width
                            linea.append(char)

                if event.type == olpcgames.CONNECT:
                    log.info( 'conectado' )
                    log.info(event)
                    log.info(dir(event))

                if event.type == pygame.USEREVENT and code == 1:
                    insertar("se agrego.. " + getNombre(event.handle), (GRAY, BLACK))

                if event.type == olpcgames.PARTICIPANT_ADD:
                    def on_buddy( buddy, event=event ):
                        amigos[event.handle] = buddy.props
                        eventwrap.post( eventwrap.Event( pygame.USEREVENT, code=1, handle=event.handle) )
                    mesh.lookup_buddy( event.handle, on_buddy )

                if event.type == olpcgames.PARTICIPANT_REMOVE:
                    insertar("se elimino.. " + getNombre(event.handle), (GRAY, BLACK))
                    del(amigos[event.handle])

            try:
                tick += 1
                if tick % 100 == 0:
                    enviar("dale boludo....") #, YELLOW)
            except:
                pass

            pygame.display.flip()

if __name__ == "__main__":
    logging.basicConfig()
    main()
